import * as api from './api';
import {
    dict,
    UserPageQuery,
    AddReq,
    DelReq,
    EditReq,
    compute,
    CreateCrudOptionsProps,
    CreateCrudOptionsRet
} from '@fast-crud/fast-crud';
import {dictionary} from '/@/utils/dictionary';
import {successMessage} from '/@/utils/message';
import {ref} from 'vue';
import {auth} from "/@/utils/authFunction";
import {useJournalStore} from "/@/stores/modules/journal";

export const createCrudOptions = function ({crudExpose, context}: CreateCrudOptionsProps): CreateCrudOptionsRet {
    const transformRes = ({res}: any) => {
        const newData = res.records
        // 根据status字段为每个元素设置enabled状态
        newData.forEach((element: any) => {
            element.enabled = Boolean(element.status); // 用 Boolean 进行转换简化逻辑
        });
        const store = useJournalStore();
        store.$patch({
            journalList: newData
        })
        // return {
        //     currentPage: 2,
        //     pageSize: 20,
        //     total: 100,
        //     records: newData
        // }

        return res
    };

    const pageRequest = async (query: UserPageQuery) => {
        let currentPage = query.page
        let pageSize = query.limit
        let total = 20033


        let params = {
            pageNum: currentPage,
            pageSize: pageSize,
            key: undefined
        }
        if (query.journal != null) {
            params.key = query.journal
        }
        const response = await api.GetList(params);
        let records = response.data

        let params2 = {
            pageNum: 1,
            pageSize: 20033,
            key: query.journal
        }
        const res = await api.GetList(params2);
        total = res.data.length;

        return {
            currentPage,
            pageSize,
            total,
            records
        };
    };
    const editRequest = async ({form, row}: EditReq) => {
        form.id = row.id;
        return await api.UpdateObj(form);
    };
    const delRequest = async ({row}: DelReq) => {
        return await api.DelObj(row.id);
    };
    const addRequest = async ({form}: AddReq) => {
        const names = [];
        names.push(form.journal)
        const newForm = {
            names: names
        }
        return await api.AddObj(newForm);
    };

    const dialogVisable = ref(false);
    const formData = ref({
        startId: '',
        endId: '',
    });

    const handleClose = () => {
        console.log("close")
        formData.value.startId = '';
        formData.value.endId = '';
    }

    const handleSubmit = async () => {
        console.log('起始ID:', formData.value.startId);
        console.log('结束ID:', formData.value.endId);

        // 可以在这里处理表单数据，例如调用 API 或其他操作
        //api.ChangeAll(BigInt(formData.value.startId), 'start', BigInt(formData.value.endId));

        // 提交后关闭弹窗
        //dialogVisable.value = false;
    };


    context.dialogVisible = dialogVisable
    context.formData = formData
    context.handleClose = handleClose()
    context.handleSubmit = handleSubmit();

    // /**
    //  * 懒加载
    //  * @param row
    //  * @returns {Promise<unknown>}
    //  */
    // const  loadContentMethod = (tree: any, treeNode: any, resolve: Function) => {
    //      pageRequest({pcode: tree.id}).then((res: APIResponseData) => {
    //         resolve(res.data);
    //     });
    // };

    return {
        crudOptions: {
            request: {
                transformRes,
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    add: {
                        show: auth('area:Create'),
                    },
                    allselect: {
                        show: true,
                        text: "全部开启",
                        click() {
                            api.ChangeAll(BigInt(1), "start", BigInt(20033));
                            useJournalStore().journalList.forEach((element: any) => {
                                if (element.enabled == false) {
                                    element.enabled = true;
                                }
                            })
                        }
                    },
                    notselect: {
                        //type:primary,
                        show: true,
                        text: "全部关闭",
                        click() {
                            api.ChangeAll(BigInt(1), "close", BigInt(20033));

                            useJournalStore().journalList.forEach((element: any) => {
                                if (element.enabled == true) {
                                    element.enabled = false;
                                }
                            })
                        }
                    },
                    selectopen: {
                        show: false,
                        text: "部分开启",
                        click() {
                            console.log("111");
                            dialogVisable.value = true;
                        }
                    }
                }
            },
            rowHandle: {
                //固定右侧
                fixed: 'right',
                width: 200,
                buttons: {
                    view: {
                        show: false,
                    },
                    edit: {
                        iconRight: 'Edit',
                        type: 'text',
                        show: auth('area:Update')
                    },
                    remove: {
                        iconRight: 'Delete',
                        type: 'text', show: auth('area:Delete')
                    },
                },
            },
            pagination: {
                show: true,

            },
            table: {
                rowKey: 'id',
                // lazy: true,
                // load: loadContentMethod,
                // treeProps: {children: 'children', hasChildren: 'hasChild'},
            },
            columns: {
                // _index: {
                //     title: '序号',
                //     show: false,
                //     form: {show: false},
                //     column: {
                //         type: 'index',
                //         align: 'center',
                //         width: '70px',
                //         columnSetDisabled: true, //禁止在列设置中选择
                //     },
                // },
                'id': {

                    title: '智能体编号',
                    key: 'id',
                    search: {
                        show: false,
                    },
                    type: 'input',
                    column: {
                        minWidth: '70px',
                        align: 'center',
                    },
                    form: {
                        // rules: [
                        //     // 表单校验规则
                        //     {required: true, message: '期刊智能体编号必填项'},
                        // ],
                        // component: {
                        //     placeholder: '请输入智能体编号',
                        // },
                        show: false,
                    },
                },
                'journal': {
                    title: '期刊智能体',
                    search: {
                        show: true,
                    },
                    key: 'journal',
                    type: 'input',
                    column: {
                        minWidth: 130,
                    },
                    form: {
                        title: '期刊名称',
                        rules: [
                            // 表单校验规则
                            {required: true, message: '名称必填项'},
                        ],
                        component: {
                            placeholder: '请输入名称',
                        },
                    },
                },
                pinyin: {
                    title: '缩写',
                    search: {
                        disabled: true,
                    },
                    type: 'input',
                    column: {
                        minWidth: 120,
                        formatter: ({row}) => {
                            // 分割字符串为单词数组
                            const words = row.journal.split(' ');
                            // 获取每个单词的首字母并拼接
                            const abbreviation = words.map((word: string) => word.charAt(0)).join('');
                            // 返回首字母缩写
                            return abbreviation;
                        }
                    },
                    form: {
                        show: false
                    },
                },
                initials: {
                    title: '首字母',
                    column: {
                        minWidth: 100,
                        formatter: ({row}) => {
                            let name = row.journal;
                            return name.charAt(0).toUpperCase();
                        }
                    },
                    form: {
                        show: false
                    },
                },
                enabled: {
                    title: '是否启用',
                    search: {
                        show: false,
                    },
                    type: 'dict-radio',
                    column: {
                        minWidth: 90,
                        component: {
                            name: 'fs-dict-switch',
                            activeText: '',
                            inactiveText: '',
                            style: '--el-switch-on-color: var(--el-color-primary); --el-switch-off-color: #dcdfe6',
                            on: {
                                onChange({row, value}) {
                                    if (value == 0) {
                                        api.SwitchControl(row.id, "start");
                                    } else {
                                        api.SwitchControl(row.id, "close");
                                    }
                                }
                            }
                        },
                    },
                    form: {
                        show: false
                    }
                },
            },
        },
    };
};
